package com.my.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.constant.UserConstants;
import com.my.handler.BusinessException;
import com.my.response.Result;
import com.my.system.entity.*;
import com.my.system.mapper.*;
import com.my.system.service.ISysUserService;
import com.my.utils.StringUtils;
import com.my.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author my
 * @since 2021-04-21
 */
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysPostMapper postMapper;
    @Autowired
    private SysUserPostMapper userPostMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;


    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return baseMapper.selectUserList(user);
    }

    @Override
    public Result findUserFactor(UserVO userVO) {
        // 对用户进行分页，泛型中注入的就是用户的实体类
        Page<SysUser> page = new Page<>(userVO.getPageNum(), userVO.getPageSize());
        QueryWrapper<SysUser> wrapper = getSysUserQueryWrapper(userVO);
        IPage<SysUser> userIPage = baseMapper.selectUserFactor(page, wrapper);
        long total = userIPage.getTotal();
        List<SysUser> records = userIPage.getRecords();
        return Result.ok("").data("total", total).data("records", records);
    }

    @Override
    public Result getInfo(Long userId) {
        // 获取角色
        List<SysRole> roles = roleMapper.selectRoleAll();
        // 获取岗位
        List<SysPost> posts = postMapper.selectPostAll();
        Result result = Result.ok("")
                .data("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()))
                .data("posts", posts);
        if (StringUtils.isNotNull(userId)) {
            List<SysUser> users = baseMapper.selectUserById(userId);
            result
                    .data("users", users)
                    .data("roleIds", roleMapper.selectRoleListByUserId(userId))
                    .data("postIds", postMapper.selectPostListByUserId(userId));
        }
        return result;
    }

    @Override
    @Transactional
    public Integer insertUser(SysUser user) {
        // 新增用户信息
        int rows = baseMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    @Override
    public String checkUserNameUnique(String userName) {
        int count = baseMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = baseMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = baseMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new BusinessException("不允许操作超级管理员用户");
        }
    }

    @Override
    @Transactional
    public Integer updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return baseMapper.updateUserById(user);
    }

    @Override
    public Integer deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            checkUserAllowed(user);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return baseMapper.deleteUserByIds(userIds);
    }

    @Override
    public Integer updateUserStatus(SysUser user) {
        return baseMapper.updateUser(user);
    }

    /**
     * @param userVO
     * @return com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.my.system.entity.SysUser>
     * @Description 根据条件查询用户列表 进行分页 用mybatis-plus
     * @Author create by yang-m 2021/4/26 0026 14:44
     */
    private QueryWrapper<SysUser> getSysUserQueryWrapper(UserVO userVO) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (null != userVO) {
            if (userVO.getDeptId() != null && userVO.getDeptId() != 0) {
                queryWrapper.eq("u.dept_id", userVO.getDeptId())
                        .or()
                        .inSql("u.dept_id", "SELECT t.dept_id FROM sys_dept t WHERE find_in_set(" + userVO.getDeptId() + ", ancestors)");
            }
            if (StringUtils.isNotEmpty(userVO.getUserName())) {
                queryWrapper.eq("u.user_name", userVO.getUserName());
            }
            if (StringUtils.isNotEmpty(userVO.getPhonenumber())) {
                queryWrapper.eq("u.phonenumber", userVO.getPhonenumber());
            }
            if (StringUtils.isNotEmpty(userVO.getStatus())) {
                queryWrapper.eq("u.status", userVO.getStatus());
            }
        }
        queryWrapper.eq("u.del_flag", 0);
        return queryWrapper;
    }

    /**
     * @param user
     * @return void
     * @Description 新增用户岗位关联
     * @Author create by yang-m 2021/4/27 0027 10:39
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * @param user
     * @return void
     * @Description 新增用户角色信息
     * @Author create by yang-m 2021/4/27 0027 10:39
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

}
